package us.icitap.commandcenter.ui.supervisor;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.vaadin.artur.icepush.ICEPush;

import us.icitap.commandcenter.CommandCenterUI;
import us.icitap.commandcenter.business.CallActionEnum;
import us.icitap.commandcenter.business.CallRolesEnum;
import us.icitap.commandcenter.business.ejb.persistence.Call;
import us.icitap.commandcenter.business.ejb.persistence.CallStatusEnum;
import us.icitap.commandcenter.listeners.ManageCallListener;
import us.icitap.commandcenter.listeners.SupervisorListener;
import us.icitap.commandcenter.ui.custom.CustVerticalLayout;
import us.icitap.commandcenter.ui.dispatcher.CallMessage;
import us.icitap.commandcenter.ui.dispatcher.UpdateVerificationWindow;
import us.icitap.commandcenter.ui.shared.CallInfoWindow;
import us.icitap.commandcenter.ui.shared.RelatedCallsWindow;
import us.icitap.commandcenter.utils.HandleNotification;
import us.icitap.utils.Result;

import com.vaadin.event.Action;
import com.vaadin.ui.Table;

import us.icitap.commandcenter.ui.shared.*;

public class SupervisorVerticalLayout extends CustVerticalLayout implements  MessageListener, SupervisorListener {

	private CloseVerificationWindow closeVerificationWindow;
	private UpdateVerificationWindow updateVerificationWindow;
	
	private ICEPush pusher = new ICEPush();
	 
	private Connection connection;
	private Session session;

	private final CallList callList = new CallList();
	private final CallForSupervisorTable callForSupervisorTable = new CallForSupervisorTable();
	
	

	public SupervisorVerticalLayout() {
		this.addExtension(pusher);
		
		this.addComponent(callForSupervisorTable);
		this.addStyleName("cust-margin-4");
		this.setWidth("900px");
		callForSupervisorTable.addActionHandler(new Action.Handler() {
            public Action[] getActions(Object target, Object sender) {
               if(target == null) return null;
               return new Action[]{GeneralVars.CLOSE_CALL, GeneralVars.SHOW_CALL_INFO};
               
            }
            
            public void handleAction(Action action, Object sender, Object target) {
            	Call call = (Call) target;
            
            	if (GeneralVars.CLOSE_CALL == action) {
            		if(closeVerificationWindow == null) 
						closeVerificationWindow = new CloseVerificationWindow(SupervisorVerticalLayout.this, call);
					else
						closeVerificationWindow.setCall(call);
                	CommandCenterUI.getCurrent().removeWindow(closeVerificationWindow);
					CommandCenterUI.getCurrent().addWindow(closeVerificationWindow);
                }
            	else if (GeneralVars.SHOW_CALL_INFO == action) {
            		CallInfoWindow ciW = new CallInfoWindow(call, callForSupervisorTable);
                	ciW.show();
            	}
               

        }});
		
		callList.addActionHandler(new Action.Handler() {
            public Action[] getActions(Object target, Object sender) {
               if(target == null) return null;
               return new Action[]{GeneralVars.ADD_INFO, GeneralVars.SHOW_CALL_INFO};
               
            }
            
            public void handleAction(Action action, Object sender, Object target) {
            	Call call = (Call) target;
            
            	if (GeneralVars.ADD_INFO == action) {
            		if(updateVerificationWindow == null) 
            			updateVerificationWindow = new UpdateVerificationWindow(SupervisorVerticalLayout.this, call);
					else
						updateVerificationWindow.setCall(call);
                	CommandCenterUI.getCurrent().removeWindow(updateVerificationWindow);
					CommandCenterUI.getCurrent().addWindow(updateVerificationWindow);
                }
            	else if (GeneralVars.SHOW_CALL_INFO == action) {
            		
            		CallInfoWindow ciW = new CallInfoWindow(call, callList.getTable());
                	ciW.show();
//                	
                	

                	
          	
                	
            	}
               

        }});
		
		
		
		this.addComponent(callList);
		
		
		startListening();
	}
	

	public void startListening(){
	    try{
	    	connection =CommandCenterUI.appStatelessBean.getConnectionFactory().createConnection();
	    	session= connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

	    	Destination dest = session.createTopic("SUPERVISOR" + CommandCenterUI.getUser().getCommandCenter().getId());
	    	MessageConsumer messageConsumer = session.createConsumer(dest);
	    	messageConsumer.setMessageListener(this);
	    	connection.start();

	    }
	    catch (JMSException e)
	    {
	      e.printStackTrace();
	    }
	   
	}
	@Override
	public void onMessage(Message message) {
		ObjectMessage objectMessage = (ObjectMessage)message;
		try {
			
			CallMessage callMessage  = (CallMessage) objectMessage.getObject();
			Call call = callMessage.getCall();
			call.setInfoDisplayed(false);
			if(call.isForSupervisor() && call.getActualStatus() == CallStatusEnum.N){
				callForSupervisorTable.addCall(call);
				HandleNotification.showInfoOnTray("Erdhi nje telefonate e re per supervizorin");
			}
			else{
				
				callList.processCall(call, callMessage.getCallActionEnum());
				if(CallActionEnum.NEW_CALL.equals(callMessage.getCallActionEnum()))
					HandleNotification.showInfoOnTray("Erdhi nje telefonate e re");
				else if(CallActionEnum.CLOSE_VERIFICATION.equals(callMessage.getCallActionEnum()) && call.getUniqueNumber() != null)
					HandleNotification.showInfoOnTray("Nje telefonate u mbyll dhe u gjenerua numri unik");
				else if (CallActionEnum.CLOSE_VERIFICATION.equals(callMessage.getCallActionEnum()))
					HandleNotification.showInfoOnTray("Nje telefonate u mbyll");
				else if (CallActionEnum.GENERATE_UN.equals(callMessage.getCallActionEnum()))
					HandleNotification.showInfoOnTray("Nje telefonate te mbyllur iu gjenerua numri unik");
				else if(CallActionEnum.START_VERIFICATION.equals(callMessage.getCallActionEnum()))
					HandleNotification.showInfoOnTray("Nje telefonate u delegua per verifikim");
				else
					HandleNotification.showInfoOnTray("Nje telefonate iu shtua informacion");
				
					
			}
			
			
			
			
			if(pusher.getUI() == null)
				this.addExtension(pusher);
				pusher.push();
	
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		
	}
	
	@Override
	public void detach() {
		CommandCenterUI.LOG.info("SupervisorVerticalLayout.detach()");
		try {
			this.session.close();
			this.connection.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.detach();
	}




	@Override
	public void updateCallInformation(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.updateCallInformation(call, CallRolesEnum.SUPERVISOR);
		if(result.isSucceeded()){
			callList.getTable().updateCall(result.getObject());
			this.updateVerificationWindow.close();
			HandleNotification.showInfoOnTray("Telefonata vazhdon te verifikohet");
		}
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
		
	}


	@Override
	public void closeCallVerification(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.closeVerification(call, CallRolesEnum.SUPERVISOR);
		if(result.isSucceeded()){
			callForSupervisorTable.removeCall(call);
			callList.processCall(call, CallActionEnum.CLOSE_VERIFICATION);
			this.closeVerificationWindow.close();
			HandleNotification.showInfoOnTray("Veirifikim i telefonates perfundoi");
		}
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
		
	}


}
